package com.googlecode.bookmarks.web;

import com.googlecode.bookmarks.core.beans.User;
import com.googlecode.bookmarks.core.exceptions.EntityNotFoundException;
import com.googlecode.bookmarks.core.service.AutentificationService;
import org.apache.wicket.Application;
import org.apache.wicket.Request;
import org.apache.wicket.authentication.AuthenticatedWebSession;
import org.apache.wicket.authorization.strategies.role.Roles;
import org.apache.wicket.injection.Injector;
import org.apache.wicket.injection.web.InjectorHolder;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.ApplicationContext;

public class BookmarksSession extends AuthenticatedWebSession {
    @SpringBean
    transient private AutentificationService autentificationService;

    public AutentificationService getAutentificationService() {
        if(autentificationService == null) {
            InjectorHolder.getInjector().inject(this);
        }
        return autentificationService;
    }

    public BookmarksSession(Request request) {
        super(request);
    }

    @Override
    public boolean authenticate(String login, String password) {
        try {
            User user = getAutentificationService().getUserByLogin(login);
            return user.getPassword().equals(password);
        } catch (EntityNotFoundException e) {
            return false;
        }
    }

    @Override
    public Roles getRoles() {
        if(isSignedIn()) {
            return new Roles(Roles.USER);
        }
        else {
            return null;
        }
    }
}
